/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-03-07 15:55:15
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:00:23
 */


'use strict';
define([
    '../../../../../modules/business/videoManage/base/baseView',
    '../../../../framework/bean/admanage',
    'text!../../tpl/monitor/table/editInnovate.html',
    '../../../../../modules/common/service',
    '../../../../../modules/model/data'
    ], function(
    BaseView,
    admanageModel,
    tpl,
    http,
    DATA
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;

        /**
         * 暂时只支持可编辑的广告类型
         * @type {string[]}
         */
        var allowObject = ["MOBILE_APP_INSTALLS", "WEBSITE_CLICKS"];

        /**
         *
         * MOBILE_APP_INSTALLS， MOBILE应用安装
         * NONE, （暂不支持）
         OFFER_CLAIMS,优惠领取 （暂不支持）
         PAGE_LIKES,  主页赞（暂不支持）
         CANVAS_APP_INSTALLS,CANVAS应用安装（暂不支持）
         EVENT_RESPONSES, 活动响应（暂不支持）
         CANVAS_APP_ENGAGEMENT,CANVAS 应用使用率（暂不支持）
         POST_ENGAGEMENT, 主页贴文互动（暂不支持）
         WEBSITE_CONVERSIONS, 网站转化（暂不支持）
         WEBSITE_CLICKS, 网站点击量
         */
        var objectiveType;
        //创意类型
        var chooseType;
        var oldChooseType;

        //图片数据  视频数据容器
        var videoData;
        var imageData;

        //ins账号
        var ins;

        //行动号召选中的值
        var callToActionVal;

        var gender = 3; //1,2,3
        var day = 2;
        var apps = [];
        var langs = [];
        var sort = [{
            "createTime": -1
        }];

        this.init = function(id, appId, appName, iconUrl, callback) {
            self.id = id;
            self.appId = appId;
            self.appName = appName;
            self.iconUrl = iconUrl;
            self.callback = callback;
            self.pageTypes = null;       //广告附带的版位
            self.promotedObject = null;  //此广告投放的应用
            self.$editAdMainPage = null; //主页
            self.$editAdTitle = null;    //标题
            self.$editAdText = null;     //文本
            self.$wAdDesc = null;        //链接文字
            self.$wAdCaption = null;     //显示网址
            self.$wAdLink = null;        //链接网址
            self.render();
        }

        this.render = function() {
            if (!$('#editInnovate')[0]) {
                $('body').append('<div id="editInnovate"></div>');
            }
            self.$el = $('#editInnovate');
            var params = {
                ad_id: self.id
            }

            admanageModel.getAd(params, function(result) {
                //1.警告不支持的编辑的广告类型
                objectiveType = result.campaign.objective;
                if($.inArray(objectiveType, allowObject) == -1){
                    Kit.alert2(I18N.getText('management','notSupportObject'));
                    return;
                }

                //2.sidepanel开始赋值 运行
                self.$el.sidepanel({
                    title:I18N.getText('management', 'editAdTitle'),
                    saveBtn: I18N.getText('management', 'saveAndClose'),
                    cancelBtn: I18N.getText('management', 'cancel'),
                    content: I18N.parse(tpl, window.pageName),
                    callback: self.updateCallback
                });
                self.$editAdMainPage = self.$el.find('select[name="editAdMainPage"]');
                self.$editAdTitle = self.$el.find('select[name="editAdTitle"]');
                self.$editAdText = self.$el.find('textarea[name="editAdText"]');
                self.$deepLink = self.$el.find('textarea[name="appDeepLink"]');
                self.$wAdDesc = self.$el.find('textarea[name="w-ad-desc"]');
                self.$wAdCaption = self.$el.find('textarea[name="w-ad-caption"]');
                self.$wAdLink = self.$el.find('textarea[name="w-ad-link"]');
                self.pageTypes = JSON.parse(result.adSet.targeting).page_types;    //mobilefeed 移动版动态消息 Mobile News Feed, instagramstream Instagram, mobileexternal 移动应用受众网络 Audience Network
                self.promotedObject = JSON.parse(result.adSet.promoted_object);
                //3.sidepanel页面事件绑定 和 所有逻辑
                self.event(result);
            })

        }

        this.event = function(result) {
            var creativeData = JSON.parse(result.creative.object_story_spec);
            var initTitle,initText,initCallToAction;
            if($.inArray('instagramstream', self.pageTypes) > -1){
                ins = result.creative.instagram_actor_id;
            }
            //判定当前广告所用创意类型
            if(creativeData.video_data){
                oldChooseType = 'video';
                chooseType = 'video';
                initTitle = creativeData.video_data.call_to_action.value.link_title;
                initText = creativeData.video_data.description;
                initCallToAction = creativeData.video_data.call_to_action.type;
                if(creativeData.video_data.call_to_action.value.app_link)
                    self.$deepLink.val(creativeData.video_data.call_to_action.value.app_link);
            } else if(creativeData.link_data.child_attachments) {
                oldChooseType = 'carousel';
                chooseType = 'carousel';
                initTitle = creativeData.link_data.child_attachments[0].call_to_action.value.link_title;
                initText = creativeData.link_data.message;
                initCallToAction = creativeData.link_data.child_attachments[0].call_to_action.type;
                if(creativeData.link_data.call_to_action.value.app_link)
                    self.$deepLink.val(creativeData.link_data.call_to_action.value.app_link);
            } else {
                oldChooseType = 'img';
                chooseType = 'img';
                initTitle = creativeData.link_data.call_to_action.value.link_title;
                initText = creativeData.link_data.message;
                initCallToAction = creativeData.link_data.call_to_action.type;
                if(creativeData.link_data.call_to_action.value.app_link)
                    self.$deepLink.val(creativeData.link_data.call_to_action.value.app_link);
            }
            //初始化主页
            self.initMainPage(creativeData.page_id);
            //初始化标题
            self.initTitle(initTitle);
            //初始化文本
            self.initText(initText);
            //行动号召
            self.initCallToAction(initCallToAction);
            //初始化图片选择
            self.initImg(creativeData);
            if(objectiveType == 'WEBSITE_CLICKS')
            {
                //外链的三个输入框
                self.initOutLink();
                $('div[name="deepLink"]').hide();
                $('div[name="outlink"]').show();
            }
            $('[data-toggle="tooltip"]').tooltip();

            //预览可选的版位
            self.initPreviewPageType();

            //预览图加载
            self.initPreviewImg();

            $('#preview-page').find('h4[name="previewAppName"]').text(self.appName);
            $('#preview-page .preview-logo').attr("src", self.iconUrl);
            $('.instgramPreview .instgramWd2').text(self.appName);
            $('.instgramPreview .instgramWd').attr("src", self.iconUrl);
            $('.instgramPreview .instgramBg').css('background-image' , 'url(./imgs/instgram.png)');
            $('.mobile').css('background-image', 'url(./imgs/mobile.png)');
            $('.mobile .headerRow .icon').attr("src", self.iconUrl);
            $('.fbAdBanner .iconContainer img').attr("src", self.iconUrl);
            //$('#preview-page .preview-image').attr("src", creativeData.link_data.picture);
            var previewPlatform = $('#preview-page').find('p[name="previewPlatform"]');
            if('itunes' === result.platform || 'itunes_pad' === result.platform)
                previewPlatform.text(I18N.getText('management', 'gotoItunes'));
            else if('google_play' === result.platform)
                previewPlatform.text(I18N.getText('management', 'gotoGooglePlay'));


            //显示高级
            $('#btn-advance').off('click').on('click', function(e) {
                var $adv =$('#dialog-advance');
                $('#btn-advance .btn-advance-text').text($adv.hasClass('in')?I18N.getText('management','openFilter'):I18N.getText('management','closeFilter'));
                $adv.collapse($adv.hasClass('in')?'hide':'show');
                $('#btn-advance i.glyphicon').toggleClass('open',$adv.hasClass('in')?'hide':'show');
            });




        }
        this.updateCallback = function($elem) {



            var pageData = self.getParams();
            if (!self.validateParams()) {
                return;
            }
            //组装后台需要的数据
            var result = new Object();
            var object_type;
            var object_story_spec = {
                page_id : pageData.page_id
            }
            if($.inArray('instagramstream', self.pageTypes) > -1){
                object_story_spec.instagram_actor_id = ins;
            }
            switch (chooseType) {
                case "img":
                    object_type = "SHARE";
                    var hash = '';
                    var imageHash = '';
                    self.$el.find('.editAd-image-div').each(function(){
                        hash = $(this).data('picture');
                        imageHash =  $(this).data('hash');
                    });
                    var link_data = {
                        multi_share_end_card : true,
                        multi_share_optimized : false,
                        link : self.promotedObject.object_store_url,
                        message : pageData.adWord
                    }
                    if(hash == '0') {
                        link_data.image_hash = imageHash;
                    } else {
                        link_data.picture = hash.replace('fbfile', 'adimage');
                    }

                    var call_to_action = {
                        type : callToActionVal
                    }
                    var value = {
                        link : self.promotedObject.object_store_url,
                        link_title : pageData.adTitle[0],
                        application : self.promotedObject.application_id
                    }
                    if(pageData.deepLink)
                        value.app_link = pageData.deepLink;
                    call_to_action.value = value;
                    link_data.call_to_action = call_to_action;
                    object_story_spec.link_data = link_data;
                    break;
                case "carousel":
                    object_type = "SHARE";
                    var link_data = {
                        multi_share_end_card : true,
                        multi_share_optimized : document.getElementById("editAdCheckBox").checked,
                        link : self.promotedObject.object_store_url,
                        message : pageData.adWord
                    }
                    var child_attachments = [];
                    var parentCallToAction;

                    self.$el.find('.editAd-image-div').each(function(m){
                        var each = {
                            link : self.promotedObject.object_store_url
                        }
                        var call_to_action = {
                            type : callToActionVal
                        }
                        var value = {
                            link : self.promotedObject.object_store_url,
                            application : self.promotedObject.application_id
                        }

                        value.link_title =  $(this).find('input').val() ? $(this).find('input').val() : pageData.adTitle[0];
                        each.name = value.link_title;
                        call_to_action.value = value;
                        each.call_to_action = call_to_action;
                        if(m == 0) {
                            parentCallToAction = {
                                type : callToActionVal
                            };
                            if(pageData.deepLink)
                                value.app_link = pageData.deepLink;
                            parentCallToAction.value = value;
                        }

                        each.picture = $(this).data('picture').replace('fbfile', 'adimage');
                        child_attachments.push(each);
                    });
                    link_data.call_to_action = parentCallToAction;
                    link_data.child_attachments = child_attachments;
                    object_story_spec.link_data = link_data;
                    break;
                case "video":
                    object_type = "VIDEO";
                    var imgurl = '';
                    var md5 = '';
                    var video_id = '';
                    self.$el.find('.editAd-image-div').each(function(i){
                        if(i == 0) {
                            md5 = $(this).data('md5');
                            video_id = $(this).data('video-id');
                        }
                        if(i == 1) {
                            imgurl = $(this).data('picture');
                        }
                    });
                    var video_data = {
                        description : pageData.adWord,
                        image_url : imgurl.replace('fbfile', 'adimage'),
                        md5 : md5
                    }
                    if(!Kit.isBlank(video_id))
                        video_data.video_id = video_id;
                    var call_to_action = {
                        type : callToActionVal
                    }
                    var value = {
                        link : self.promotedObject.object_store_url,
                        link_title : pageData.adTitle[0],
                        application : self.promotedObject.application_id
                    }
                    if(pageData.deepLink)
                        value.app_link = pageData.deepLink;
                    call_to_action.value = value;
                    video_data.call_to_action = call_to_action;
                    object_story_spec.video_data = video_data;
                    break;
            }
            result.object_type = object_type;
            result.object_story_spec = object_story_spec;

            var params = {
                ad_id: self.id,
                job_type: 'update_ad_creative',
                value: JSON.stringify(result)
            }
            admanageModel.updateAd(params, function(result) {
                self.callback(result, 1, self.queryStatusOK, self.queryStatusFail); //调用 table.js queryStatus
            });
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusOK
         * @param      {<type>}  result  { description }
         */
        this.queryStatusOK = function(result) {
            console.info(result)
            self.$el.sidepanel('hide');
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusFail
         * @param      {<type>}  result  { description }
         */
        this.queryStatusFail = function(result) {
            console.info(result)
        }


        /**
         * { 获取参数 }
         *
         * @method     getPanelParams
         */
        this.getParams = function() {
            var params = {};
            params.page_id = $('select[name="editAdMainPage"] option:selected').val();
            params.adTitle = self.$editAdTitle.val();
            params.adWord = self.$editAdText.val();
            params.deepLink = self.$deepLink.val();
            params.wAdDesc = self.$wAdDesc.val();
            params.wAdCaption = self.$wAdCaption.val();
            params.wAdLink = self.$wAdLink.val();
            //params.billing_event = self.$billing.find('input').attr('data-val');
            //params.bid_amount = self.Kit.isBlank(self.$bidAmountVal.val()) ? '' : self.$bidAmountVal.val() * 100; //转为美分
            return params;
        }


        /**
         * { 验证参数 }
         *
         * @method     validateParams
         */
        this.validateParams = function() {
            var params = self.getParams();
            if (Kit.isBlank(params.page_id) || params.page_id == '-1') {
                Kit.alert2(I18N.getText('management','inputPage'));
                return false;
            }
            if (Kit.isBlank(params.adTitle)) {
                Kit.alert2(I18N.getText('management','inputHeadline'));
                return false;
            }
            if (Kit.isBlank(params.adWord)) {
                self.$editAdText.testRemind(I18N.getText('management','notEmpty'));
                self.$editAdText.focus();
                return false;
            }
            var imgDiv = self.$el.find('.editAd-image-div');
            if(imgDiv.length < 1) {
                Kit.alert2(I18N.getText('management','selectImg'));
                return false;
            }
            if(chooseType == 'video') {
                if(imgDiv.length < 2) {
                    Kit.alert2(I18N.getText('management','selectImg'));
                    return false;
                }
            }
            var carouselImgTitle = false;
            if(chooseType == 'carousel') {
                imgDiv.each(function(k){
                    if($(this).find('input').val().length > 40){
                        Kit.alert2(I18N.getText('management','liteImgTitleTooLong', k+1));
                        carouselImgTitle = true;
                    }
                });
            }
            if(carouselImgTitle)
                return false;

            if(objectiveType === 'WEBSITE_CLICKS')
            {
                if (Kit.isBlank(params.wAdDesc)) {
                    self.$wAdDesc.testRemind(I18N.getText('management','notEmpty'));
                    self.$wAdDesc.focus();
                    return false;
                }
                if (Kit.isBlank(params.wAdCaption)) {
                    self.$wAdCaption.testRemind(I18N.getText('management','notEmpty'));
                    self.$wAdCaption.focus();
                    return false;
                }
                if (Kit.isBlank(params.wAdLink)) {
                    self.$wAdLink.testRemind(I18N.getText('management','notEmpty'));
                    self.$wAdLink.focus();
                    return false;
                }
            }
            return true;
        }
        /*
         @初始化预览可选的版位
         */
        this.initPreviewPageType = function(){
            var $adPreviewPageType = $('div[name="AdPreviewTitle"]');
            $.each(self.pageTypes, function(k, v){
                if(v == 'mobileexternal') {
                    $adPreviewPageType.after('<div><span class="btn-preview-pagetype" data-pagetype="'+v+'banner">'+ I18N.getText('management', (v+'banner')) +'</span></div>');
                    $adPreviewPageType.after('<div><span class="btn-preview-pagetype" data-pagetype="'+v+'stream">'+ I18N.getText('management', (v+'stream')) +'</span></div>');
                    $adPreviewPageType.after('<div><span class="btn-preview-pagetype" data-pagetype="'+v+'old">'+ I18N.getText('management', (v +'old')) +'</span></div>');
                    //fbAdBanner 轮播
                    var index =0;
                    //3秒轮播一次
                    var timer = setInterval(function(){
                        index = (index == 2) ? 0 : index + 1;
                        //某个div显示，其他的隐藏
                        $(".card").hide().eq(index).show();
                    }, 3000);
                } else {
                    $adPreviewPageType.after('<div><span class="btn-preview-pagetype" data-pagetype="'+v+'">'+ I18N.getText('management', v) +'</span></div>');
                }

            });

            $('#editInnovate div[name="previewEachDiv"]').hide();
            self.$el.find('.btn-preview-pagetype:eq(0)').addClass('active');
            $('#preview-page').show();
            self.$el.find('.btn-preview-pagetype').off('click').on('click', function() {
                self.$el.find('.btn-preview-pagetype').removeClass('active');
                $(this).addClass('active');
                $('#editInnovate div[name="previewEachDiv"]').hide();
                if($(this).data('pagetype') == 'instagramstream') {
                    $('#editInnovate .instgramPreview').show();
                    var imgSrc = $('#editAdImageDiv .editAd-image-div:not(.player-video) img.editAd-image').attr('src');
                    $('.instgramImg').attr('src', imgSrc);
                    if($('input[value=video]').prop('checked')){
                        if($('.instgramPreview .shipinCircle').length==0){
                            $('.instgramPreview .instgramImg').after('<div class="shipinCircle" style="background-image: url(./imgs/shipin.png);"></div>');
                        }
                    }else{
                        $('.instgramPreview .shipinCircle').remove();
                    }
                } else if($(this).data('pagetype') == 'mobileexternalbanner') {
                    $('#editInnovate .fbbanner').show();
                } else if($(this).data('pagetype') == 'mobileexternalstream'){
                    $('#editInnovate .mobile').show();
                    var imgSrc = $('#editAdImageDiv .editAd-image-div:not(.player-video) img.editAd-image').attr('src');
                    $('.mobile[name=previewEachDiv] .bannerRow').css('background-image','url("'+imgSrc+'")')
                    if($('input[value=video]').prop('checked')){
                        if($('.mobile .iconRow .shipinCircle').length==0){
                            var imgSrc = $('#editAdImageDiv .editAd-image-div:not(.player-video) img.editAd-image').attr('src');
                            $('.mobile[name=previewEachDiv] .bannerRow').css('background-image','url("'+imgSrc+'")')
                            $('.mobile .iconRow').append('<div class="shipinCircle" style="background-image: url(./imgs/shipin.png);"></div>');
                            $('.mobile .iconRow .shipinCircle').css({
                                top:'-220px',
                                left:''
                            })
                        }
                    }else{
                        $('.mobile .iconRow .shipinCircle').remove();
                    }
                } else {
                    $('#preview-page').show();
                }

                $('.preview-banner').toggleClass('hidden',$(this).data('pagetype') != 'mobilefeed');
            });
        }
        /*
         @轮播图可拖拽
         */
        this.carouselDrag = function(){
            $("#editAdImageDiv").dragsort("destroy");
            $("#editAdImageDiv").dragsort({
                dragSelector: "li",
                dragEnd: function() {
                    $("#editAdImageDiv li").each(function(i,v){
                        $(this).attr('data-index',i);
                    });
                },
                replaceItemExcludeClass:"tab-pane-cell",
                placeHolderTemplate: "<li></li>"
            });

        }
        /*
         @初始化主页
         */
        this.initMainPage = function(pageId){
            var _mainPage = $('select[name="editAdMainPage"]');
            http.work('/page/getPages','POST').then(function(res){
                var data = res.data;
                if(res.flag == 'success'){
                    data = _.sortBy(data,function (item) {return item.name.toLowerCase();});
                    var tmpHtml = '<option value="-1">' + I18N.getText('adPublishCondition','selectPage') + '</option>';
                    var pageIdNotInPages = true;
                    for(var i = 0; i<data.length; i++){
                        if(pageId == data[i].fbPageId)
                        {
                            pageIdNotInPages = false;
                            tmpHtml += '<option img="'+data[i].pictureUrl+'" request-link="'+data[i].link+'" selected="selected" value="'+data[i].fbPageId+'">'+data[i].name+'</option>';
                        }
                        else
                        {
                            tmpHtml += '<option img="'+data[i].pictureUrl+'" request-link="'+data[i].link+'" value="'+data[i].fbPageId+'">'+data[i].name+'</option>';
                        }
                    }
                    if(pageIdNotInPages)
                        tmpHtml += '<option selected="selected" value="-1">' + I18N.getText('management','unknownPage') + '</option>';

                    _mainPage.html(tmpHtml);
                    _mainPage.select2({
                        //打开
                        templateResult: function(item){
                            if(!item.id || item.id == -1){
                                return item.text;
                            }
                            var _t =  '<span><img src="' + $(item.element).attr("img")
                                + '" style="height: 20px;width: 20px;" /> ' +item.text + '</span>'
                            return $(_t);
                        },
                        //选中
                        templateSelection: function(item){
                            if(!item.id ||item.id == -1){
                                return item.text;
                            }
                            return $('<span><img src="' + $(item.element).attr("img") + '" style="height: 20px;width: 20px;" />'+ item.text + '</span>');
                        }
                    });
                }else{
                    Kit.alert2(res.msg || I18N.getText('adPublishCondition','getPagesFailed'))
                }
            });
        }

        /*
         @初始化标题
         */
        this.initTitle = function(title){
            $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank(title)? '&nbsp;' : title);
            $('.fbAdBanner .cardContainer .title').text(title);
            $('.mobile .titleRow .title').text(title);
            var _adTitle = $('select[name="editAdTitle"]');
            var getTitleParams = {
                typeId: self.appId
            }
            admanageModel.getAdTitleHistory(getTitleParams, function(result) {
                var tmpHtml = '';
                var titleNotInHistory = true;
                if(result){
                    $.each(result, function(i, v){
                        if(v.title == title) {
                            titleNotInHistory = false;
                            tmpHtml += '<option selected="selected">' + v.title + '</option>';
                        } else {
                            tmpHtml += '<option>' + v.title + '</option>';
                        }
                    });
                }

                if(titleNotInHistory)
                {
                    tmpHtml += '<option selected="selected">' + title + '</option>';
                }
                _adTitle.html(tmpHtml);
                _adTitle.select2({
                    tags:true,
                    //打开
                    templateResult: function(item){
                        if(!item.id || item.id == -1){
                            return item.text;
                        }
                        var _t =  '<span>' +item.text + '</span>'
                        return $(_t);
                    },
                    minimumResultsForSearch: Infinity,
                    maximumSelectionLength: 1,
                    //选中
                    templateSelection: function(item){
                        if(!item.id ||item.id == -1){
                            return item.text;
                        }
                        return $('<span>'+ item.text + '</span>');
                    }
                });
                _adTitle.on("change", function (e) {
                    if($('input[value=carousel]').prop('checked')){//轮播图取图片的title
                        return;
                    }
                    $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($(this).val())? '&nbsp;' : $(this).val());
                    $('.fbAdBanner .cardContainer .title').text($(this).val());
                    $('.mobile .titleRow .title').text($(this).val());
                });
            }, function(){
                var tmpHtml = '<option selected="selected">' + title + '</option>';
                _adTitle.html(tmpHtml);
                _adTitle.select2({
                    tags:true,
                    //打开
                    templateResult: function(item){
                        if(!item.id || item.id == -1){
                            return item.text;
                        }
                        var _t =  '<span>' +item.text + '</span>'
                        return $(_t);
                    },
                    minimumResultsForSearch: Infinity,
                    maximumSelectionLength: 1,
                    //选中
                    templateSelection: function(item){
                        if(!item.id ||item.id == -1){
                            return item.text;
                        }
                        return $('<span>'+ item.text + '</span>');
                    }
                });
                _adTitle.on("change", function (e) {
                    $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($(this).val())? '&nbsp;' : $(this).val());
                    $('.fbAdBanner .cardContainer .title').text($(this).val());
                    $('.mobile .titleRow .title').text($(this).val());
                });
            });
        }

        /*
         @初始化广告词
         */
        this.initText = function(text){
            $('.fbAdBanner .contentContainer .card3 .body').html(Kit.isBlank(text)? '&nbsp;' :text);
            $('#bodyRow').html(Kit.isBlank(text)? '&nbsp;' :text);
            var _adTitle = $('textarea[name="editAdText"]');
            _adTitle.val(text).off("input").on('input', function(){
                var tlval = Kit.isBlank($(this).val())? '&nbsp;' : $(this).val();
                $('#preview-page .preview-ad-txt').html(tlval);
                $('.instgramPreview .instgramFootText span').html(tlval);
                $('.fbAdBanner .contentContainer .card3 .body').html(tlval);
                $('#bodyRow').html(tlval);
                var len = $(this).val().length;
                if(len==0){
                    $(this).next(".text-range-warning").text("");
                    //不能保存
                    //node.find(".save-slogan").("disabled");
                }else if(len < 90){
                    $(this).next(".text-range-warning").text(I18N.getText('createAd', 'canAlsoEnter',300-len));
                }
                else if(len>=90 && len<300){
                    $(this).next(".text-range-warning").text(I18N.getText('createAd','warnHidden', 90));
                }
                else if(len >=300){
                    $(this).next(".text-range-warning").text(I18N.getText('createAd','hasReached',300));
                }

                if (Kit.isAr($(this).val())) {
                    $(this).attr('dir', 'rtl');
                } else {
                    $(this).removeAttr('dir', 'rtl');
                }
            });
            _adTitle.trigger("input");
        }

        /*
         @行动号召
         */
        this.initCallToAction = function(callToAction){
            var opt = DATA.callToActions.app;
            callToActionVal = callToAction;
            var previewCallToAction = $('#preview-page').find('button[name="previewCallToAction"]');
            var previewInstgramCallToAction = $('.instgramPreview .instgramCallToAction');
            var previewFbAdBannerCallToAction = $('.fbAdBanner .placeholderContainer .buttonText');
            var previewMobileCallToAction = $('.mobile .actionButtonRow .ctaQuestion');
            for (var i = 0; i < opt.length; i++) {
                if (opt[i].value == callToAction) {
                    previewCallToAction.text(opt[i].text);
                    previewInstgramCallToAction.text(opt[i].text);
                    previewFbAdBannerCallToAction.text(opt[i].text);
                    previewMobileCallToAction.text(opt[i].text);
                }
            }

            $("#actioncall").drop({
                data:opt,
                name:"actioncallD"
            }).on("ITEM_CLICK",function(e){
                previewCallToAction.text(e.originalEvent.data.text);
                previewInstgramCallToAction.text(e.originalEvent.data.text);
                previewFbAdBannerCallToAction.text(e.originalEvent.data.text);
                previewMobileCallToAction.text(e.originalEvent.data.text);
                callToActionVal = e.originalEvent.data.val;
            }).val(Kit.keyInReturnText(opt,callToAction,"value")); //设置 显示在input 里面的值
        }

        /*
         @初始化图片选择
         */
        this.initImg = function(creativeData){
            $('input[name="asset1"][value='+chooseType+']').attr("checked",true); //刚进来选中的素材类型

            var previewImgDiv = $('#focus ul');
            var previewInstgramImg = $('.instgramPreview .instgramImg');
            var previewMobileImg = $('.mobile .contentArea .bannerRow');
            switch (chooseType) {
                case "img":
                    var imageShow = (creativeData.local_picture_url ? creativeData.local_picture_url : creativeData.picture );
                        var eachImg = '<li><div class="editAd-image-div" data-hash="'+creativeData.link_data.image_hash + '" data-picture="'+(creativeData.link_data.picture ? creativeData.link_data.picture :'0') +'"><img class="editAd-image" src="'+ imageShow+'" /></div></li>';
                            previewImgDiv.append('<li><img src="'+ imageShow +'" /></li>');
                            previewInstgramImg.attr('src', imageShow);
                        previewMobileImg.css('background-image' , 'url('+imageShow+')');
                        $('#editAdImageDiv').html(eachImg);
                        $('#editAdImageDiv').css('height', '130px');
                    $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                    break;
                case "carousel":
                    if(creativeData.link_data.child_attachments)
                    {
                        var eachImg = '';
                        $.each(creativeData.link_data.child_attachments, function(i, v){
                            eachImg += '<li><div class="editAd-image-div" data-picture="'+ v.picture +'"><img class="editAd-image" src="'+ (v.local_picture_url? v.local_picture_url: v.picture) +'" /><input type="text" class="form-control" value="'+ v.call_to_action.value.link_title +'" /></div></li>';
                            previewImgDiv.append('<li><img src="'+(v.local_picture_url? v.local_picture_url: v.picture) +'" /></li>');
                            previewInstgramImg.attr('src', v.picture);
                            previewMobileImg.css('background-image' , 'url('+(v.local_picture_url? v.local_picture_url: v.picture)+')');

                        });
                        if(creativeData.link_data.child_attachments.length > 3)
                            $('#editAdImageDiv').css('height', '260px');
                        else
                            $('#editAdImageDiv').css('height', '130px');
                        $('#editAdImageDiv').html(eachImg);
                        //轮播图初始化  是否只是自动图片排序
                        $("#editInnovate input[type='checkbox']").attr('checked', creativeData.link_data.multi_share_optimized);
                    }
                    $('div[name="creativeOptDiv"]').show();
                    self.carouselDrag();
                    $("#editAdImageDiv li").hover( function(event){
                        $(this).addClass('editAdImageDivHover');
                    },function(event){
                        $(this).removeClass('editAdImageDivHover');
                    });
                    // ins广告不支持轮播图
                    if(self._.indexOf(self.pageTypes, 'instagramstream')>-1){
                        $('[data-target="#carousel"] input').prop('disabled',true);
                        $('.btn-innovation-change-image').addClass('disabled').attr('disabled', true);
                    }

                    break;
                case "video":
                    var eachImg = '<li><div class="editAd-image-div player-video" data-video-id="'+creativeData.video_data.video_id+'" data-video-url="'+(creativeData.local_video_url ? creativeData.local_video_url : '0') +'"><i class="glyphicon glyphicon-play-circle"></i><img class="editAd-image" src="'+ (creativeData.local_picture_url?creativeData.local_picture_url:creativeData.video_data.image_url) +'"></div></li>';
                        previewImgDiv.append('<li><img src="'+(creativeData.local_picture_url?creativeData.local_picture_url:creativeData.video_data.image_url) +'" /><div class="shipinCircle"></div></li>');
                        previewInstgramImg.attr('src', (creativeData.local_picture_url?creativeData.local_picture_url:creativeData.video_data.image_url));
                    previewMobileImg.css('background-image' , 'url('+(creativeData.local_picture_url?creativeData.local_picture_url:creativeData.video_data.image_url)+')');
                    eachImg += '<li><div class="editAd-image-div" data-picture="'+ creativeData.video_data.image_url +'"><img class="editAd-image" src="'+ (creativeData.local_picture_url?creativeData.local_picture_url:creativeData.video_data.image_url) +'"></div></li>';
                    $('#editAdImageDiv').html(eachImg);
                    $('.shipinCircle').css('background-image', 'url(./imgs/shipin.png)');
                    $('#editAdImageDiv').css('height', '130px');
                    $('#editAdImageDiv li').css('width', '140px');
                    $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                    break;
            }
            //切换素材类型
            $("#asset-choose").off("click").on('click', function(e) {
                chooseType = $('#innovation input:radio:checked').val();
                $('.btn-preview-pagetype:first').trigger('click');
                switch (chooseType) {
                    case "img":
                        $('.btn-innovation-change-image').removeClass('disabled').removeAttr('disabled', true);
                        $('div[name="creativeOptDiv"]').hide();
                        if(oldChooseType == 'img')
                        {
                            var imageShow = (creativeData.link_data.picture ? creativeData.link_data.picture : creativeData.local_picture_url );
                            var eachImg = '<li><div class="editAd-image-div" data-hash="'+creativeData.link_data.image_hash + '" data-picture="'+(creativeData.link_data.picture ? creativeData.link_data.picture :'0') +'"><img class="editAd-image" src="'+ imageShow+'" /></div></li>';
                            previewImgDiv.html('<li><img src="'+ imageShow +'" /></li>');
                            previewInstgramImg.attr('src', imageShow);
                            previewMobileImg.css('background-image' , 'url('+imageShow+')');
                            $('#editAdImageDiv').html(eachImg);
                        }
                        else
                        {
                            previewImgDiv.html('<li><img src="" /></li>');
                            previewInstgramImg.attr('src', '');
                            previewMobileImg.attr('src', '');
                            $('#editAdImageDiv').empty();
                        }
                        $('#editAdImageDiv').css('height', '130px');
                        $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                        $("#selectslogan .modal-footer .pre").addClass('hidden');
                        if($('[name=editAdTitle]').val()){
                            $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                        }

                        break;
                    case "carousel":
                        $('div[name="creativeOptDiv"]').show();

                        if(oldChooseType == 'carousel')
                        {
                            var eachImg = '';
                            $.each(creativeData.link_data.child_attachments, function(i, v){
                                eachImg += '<li><div class="editAd-image-div" data-picture="'+ v.picture +'"><img class="editAd-image" src="'+ v.picture +'"><input type="text" class="form-control" value="'+ v.call_to_action.value.link_title +'"></div></li>';
                                previewImgDiv.append('<li><img src="'+ v.picture +'" /></li>');
                                previewInstgramImg.attr('src', v.picture);
                                previewMobileImg.css('background-image' , 'url('+v.picture+')');
                            });
                            $('#editAdImageDiv').html(eachImg);
                            if(creativeData.link_data.child_attachments.length > 3)
                                $('#editAdImageDiv').css('height', '260px');
                            else
                                $('#editAdImageDiv').css('height', '130px');
                        }
                        else
                        {
                            previewImgDiv.html('<li><img src="" /></li>');
                            previewInstgramImg.attr('src', '');
                            previewMobileImg.attr('src', '');
                            $('#editAdImageDiv').empty();
                            $('#editAdImageDiv').css('height', '130px');
                        }
                        $("#selectslogan .modal-footer .pre").addClass('hidden');
                        $("#editAdImageDiv li").hover( function(event){
                            $(this).addClass('editAdImageDivHover');
                        },function(event){
                            $(this).removeClass('editAdImageDivHover');
                        });
                         $('#editAdImageDiv').empty().height(130);
                        self.carouselDrag();
                        break;
                    case "video":
                        $('.btn-innovation-change-image').removeClass('disabled').removeAttr('disabled', true);
                        $('div[name="creativeOptDiv"]').hide();
                        if(oldChooseType == 'video')
                        {
                            var eachImg = '<li><div class="editAd-image-div player-video" data-video-id="'+creativeData.video_data.video_id+'" data-video-url="'+(creativeData.local_video_url ? creativeData.local_video_url : '0') +'"><i class="glyphicon glyphicon-play-circle"></i><img class="editAd-image" src="'+ (creativeData.local_video_url ? creativeData.local_video_url : creativeData.video_data.image_url) +'"></div></li>';
                            previewImgDiv.html('<li><img src="'+ creativeData.video_data.image_url +'" /><div class="shipinCircle"></div></li>');
                            previewInstgramImg.attr('src', creativeData.video_data.image_url);
                            previewMobileImg.css('background-image' , 'url('+creativeData.video_data.image_url+')');
                            eachImg += '<li><div class="editAd-image-div" data-picture="'+ creativeData.video_data.image_url +'"><img class="editAd-image" src="'+ creativeData.video_data.image_url +'"></div></li>';
                            $('#editAdImageDiv').html(eachImg);
                        }
                        else
                        {
                            previewImgDiv.html('<li><img src="" /><div class="shipinCircle"></div></li>');
                            previewInstgramImg.attr('src', '');
                            previewMobileImg.attr('src', '');
                            $('#editAdImageDiv').empty();
                        }
                        $('.shipinCircle').css('background-image', 'url(./imgs/shipin.png)');
                        $('#editAdImageDiv').css('height', '130px');
                        $('#editAdImageDiv li').css('width', '140px');
                        $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                        if($('[name=editAdTitle]').val()){
                            $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                        }
                        break;
                }
                self.initPreviewImg();
            });
            //绑定更换素材 按钮事件
            $('#innovation').off("click", 'button[name="innovationChange"]').on('click', 'button[name="innovationChange"]', function(e) {
                //初始化 选择图片modal
                self.initImageModal();
                $(".dia-lang").val(null).trigger("change");
                $("div.pic-pool ul.nav-pills>li[role]>a").each(function(index, el) {
                    if(index == 0)
                        $(this).text($(this).data('sort-title'));
                    else
                        $(this).text($(this).data('title'));
                });
                $("div.pic-pool ul.nav-pills>li:eq(1)").addClass("active").siblings().removeClass("active");
                chooseType = $('#innovation input:radio:checked').val();
                switch (chooseType) {
                    case "img":
                    case "carousel":
                        $('#selectslogan').modal('show');
                        break;
                    case "video":
                        $("#selectVideoModal .modal-footer .btn-primary").addClass('hidden'); //选择视频刚进来下一步都是隐藏的
                        $("#selectslogan .modal-footer .pre").removeClass('hidden'); //上一步按钮接触隐藏
                        $('#selectVideoModal').modal('show');
                        $('#selectslogan').modal('hide');
                        break;
                }
            });
            self.$el.off('click', '.player-video').on('click', '.player-video', $.proxy(self.playerVideo, self));
        }
        /*
         @初始化 预览图
         */
        this.initPreviewImg = function() {
            var sWidth = $("#focus").width();
            var len = $("#focus ul li").length;
            if(len <= 1) {
                $("#focus ul").css('width', '300px');
                $("#focus ul").nextAll().remove();
                return;
            }
            var index = 0;
            var picTimer;
            var btn = "<div class='btnBg'></div><div class='btn'>";
            for (var i = 0; i < len; i++) {
                btn += "<span></span>";
            }
            btn += "</div><div class='preNext pre'></div><div class='preNext next'></div>";
            $("#focus").append(btn);
            $("#focus .btnBg").css("opacity", 0);
            $("#focus .btn span").css("opacity", 0.4).mouseenter(function () {
                index = $("#focus .btn span").index(this);
                showPics(index);
            }).eq(0).trigger("mouseenter");
            $("#focus .preNext").css("opacity", 0.0).hover(function () {
                $(this).stop(true, false).animate({ "opacity": "0.5" }, 300);
            }, function () {
                $(this).stop(true, false).animate({ "opacity": "0" }, 300);
            });
            $("#focus .pre").css('background', 'url(./imgs/sprite.png) no-repeat left center');
            $("#focus .pre").click(function () {
                index -= 1;
                if (index == -1) { index = len - 1; }
                showPics(index);
            });
            $("#focus .next").css('background', 'url(./imgs/sprite1.png) no-repeat right center');
            $("#focus .next").click(function () {
                index += 1;
                if (index == len) { index = 0; }
                showPics(index);
            });
            $("#focus ul").css("width", sWidth * (len));
            $("#focus").hover(function () {
                clearInterval(picTimer);
            }, function () {
                //picTimer = setInterval(function () {
                //    showPics(index);
                //    index++;
                //    if (index == len) { index = 0; }
                //}, 2800);
            }).trigger("mouseleave");
            function showPics(index) {
                var nowLeft = -index * sWidth;
                $("#focus ul").stop(true, false).animate({ "left": nowLeft }, 300);
                $("#focus .btn span").stop(true, false).animate({ "opacity": "0.4" }, 300).eq(index).stop(true, false).animate({ "opacity": "1" }, 300);
            }




            $('#editAdImageDiv').off('keyup','input.form-control:first').on('keyup','input.form-control:first',function() {
                if(Kit.isBlank($(this).val())){
                    $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                }else{
                    $('#preview-page').find('h4[name="previewAdTitle"]').html($(this).val());
                }
            })


        }
        /*
         @初始化 选择图片modal
         */
        this.initImageModal = function(){
            //---------start  每次打开图片窗口，重置------------
            gender = 3; //全部
            apps = [self.appName];
            langs = []; //默认语言为空
            day = 2; //默认2天
            sort = [{
                "createTime": -1
            }];
            //---------end  每次打开图片窗口，重置------------
            var body = {
                param: {}
            };
            if (chooseType == "video") {
                //请求视频
                self.updateVideo();
            }
            self.update();

            http.do("/connectionobjects/searchConnectionObjectsByResourceManage", {param: JSON.stringify({typeId: 2})})
                .then(function (result) {
                    if (typeof(result) == "string") result = JSON.parse(result);
                    var resourApps = $.map(result.data,function(v){
                        v.text = v.name;
                        return v;
                    });
                    $("#selectslogan .modal-body select.dia-app").select2({
                        data: resourApps
                    }).off("select2:select").on("select2:select", function(e) {
                        apps.push(e.params.data.name ? e.params.data.name : e.params.data.text);
                        self.update();
                    }).off("select2:unselect").on("select2:unselect", function(e) {
                        var index = apps.indexOf(e.params.data.name);
                        apps.splice(index, 1);
                        self.update();
                        //当点击删除tag 的时候,不让打开下拉选择
                        if (e.params.originalEvent && e.params.originalEvent.target.className == 'select2-selection__choice__remove') {
                            e.params.originalEvent.stopPropagation();
                        }
                    }).select2("val", self.appId);

                    // 视频搜索
                    var $videoAppSelect = $("#selectVideoModal .modal-body select.dia-video-app");
                    if ($videoAppSelect[0]) {
                        $("#selectVideoModal .modal-body select.dia-video-app").select2({
                            data: resourApps
                        }).off("select2:select").on("select2:select", function(e) {
                            var params = [];
                            $('#selectVideoModal .modal-body .dia-video-app option:selected').each(function(index, el) {
                                params.push($(this).text())
                            });
                            params.push(self.appName)
                            self.updateVideo(params);
                        }).off("select2:unselect").on("select2:unselect", function(e) {
                            var params = [];
                            $('#selectVideoModal .modal-body .dia-video-app option:selected').each(function(index, el) {
                                params.push($(this).text())
                            });
                            params.push(self.appName)
                            self.updateVideo(params);
                            //当点击删除tag 的时候,不让打开下拉选择
                            if (e.params.originalEvent && e.params.originalEvent.target.className == 'select2-selection__choice__remove') {
                                e.params.originalEvent.stopPropagation();
                            }
                        }).select2("val", self.appId);
                    }
                }, function (err) {

                });

            //语言
            $("#selectslogan .modal-body select.dia-lang").select2({
                ajax: http.s2AJAX("/search/searchAdlocale", {
                    type: "adlocale",
                    locale: I18N.language
                }, {
                    idkey: "key",
                    textKey: "name"
                }),
                minimumInputLength: 1,
                multiple: true
            }).off("select2:select").on("select2:select", function(e) {
                langs.push(e.params.data.name);
                self.update();
            }).off("select2:unselect").on("select2:unselect", function(e) {
                var index = langs.indexOf(e.params.data.name);
                langs.splice(index, 1);
                self.update();
            });

            $("#selectslogan .modal-body select.filter").select2({
                data: [{
                    id: 1,
                    text: I18N.getText('createAd', 'recentlyDay', 1)
                }, {
                    id: 2,
                    text: I18N.getText('createAd', 'recentlyDay', 2)
                }, {
                    id: 3,
                    text: I18N.getText('createAd', 'recentlyDay', 3)
                }, {
                    id: 7,
                    text: I18N.getText('createAd', 'recentlyDay', 7)
                }]
            }).off("select2:select").on("select2:select", function(e) {
                day = e.params.data.id;
                self.update();
            }).select2("val", 2);

            //性别
            $("#selectslogan .modal-body .dia-gender").empty().drop({
                data:[{
                    value: 1,
                    text: I18N.getText('createAd', 'men')
                }, {
                    value: 2,
                    text: I18N.getText('createAd', 'women')
                }, {
                    value: 3,
                    text: I18N.getText('createAd', 'all')
                }],
                name:"modelSex"//为了方便serialize 建议设置name 属性
            }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){//下拉选择项点击事件
                //返回的数据有
                gender = e.originalEvent.data.val;
                self.update();
            }).val(I18N.getText('createAd', 'all')); //设置 显示在input 里面的值


            $("div.pic-pool ul.nav-pills>li[role]>a").off('click').on('click', function() {
                var tag = $(this).attr("type");
                sort = [{}];
                sort[0][tag] = -1;
                self.update();
                $("div.pic-pool ul.nav-pills>li[role]>a").each(function(index, el) {
                    $(this).text($(this).data('title'));
                });
                $(this).text($(this).data('sort-title'));
            });
            //轮播图不需要显示排序条件
            if (chooseType == 'carousel') {
                $("#selectslogan[role=dialog] .modal-body .pic-pool .filter-tool").addClass('hidden');
                $("#selectslogan[role=dialog] .modal-body .pic-pool .select2").addClass('hidden');
            } else {
                $("#selectslogan[role=dialog] .modal-body .pic-pool .filter-tool").removeClass('hidden');
                $("#selectslogan[role=dialog] .modal-body .pic-pool .select2").removeClass('hidden');
            }

            //选择创意模态-点击保存
            $("#selectVideoModal .modal-footer .btn-primary").off('click').on('click', function() {
                var selectedVideo = $('#selectVideoModal ul.vid-list-box>li.active');
                selectedVideo.each(function() {
                    var eachImg = '<li><div class="editAd-image-div player-video" data-md5="'+$(this).data('md5')+'" data-video-url="'+$(this).data('visitpath')+'"><i class="glyphicon glyphicon-play-circle"></i><img class="editAd-image" src="'+ $(this).data('litimgurl') +'"></div></li>';
                    $('#editAdImageDiv').empty();
                    $('#editAdImageDiv').html(eachImg);
                });
                $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                $('#selectVideoModal').modal('hide');
                $("#selectslogan").modal('show');

            });

            //选择创意模态-点击上一步
            $("#selectslogan .modal-footer .pre").off('click').on('click', function() {
                $("#selectslogan").modal('hide');
                $('#selectVideoModal').modal('show');
            });

            //选择创意模态-点击保存
            $("#selectslogan .modal-footer .btn-primary").off('click').on('click', function() {
                var len = $('#selectslogan .container-fluid.active').length;
                if(len < 1) {
                    Kit.alert2(I18N.getText('createAd', 'selectMaterial'));
                    return;
                }
                if(chooseType == 'carousel') {
                    if (len < 3) {
                        Kit.alert2(I18N.getText('createAd', 'minSelectSlider', 3));
                        return;
                    } else if(len > 3) {
                        $('#editAdImageDiv').css('height', '260px');
                    }
                }
                var eachImg = '';
                var selectedImg = $('#selectslogan .container-fluid.active');
                var previewImgDiv = $('#focus ul');  //预览的 也联动
                var previewInstgramImg = $('.instgramPreview .instgramImg');
                var previewMobileImg = $('.mobile .contentArea .bannerRow');
                previewImgDiv.empty();
                selectedImg.each(function(){
                    var imgId = $(this).data('imgid');
                    $.each(imageData, function(i, v){
                        if(v.id === imgId){
                            switch (chooseType) {
                                case "img":
                                    eachImg += '<li><div class="editAd-image-div" data-picture="' + v.visitPath + '"><img class="editAd-image" src="' + v.litImgURL + '"></div></li>';
                                    previewImgDiv.append('<li><img src="'+ v.visitPath +'" /></li>');
                                    previewInstgramImg.attr('src', v.visitPath);
                                    previewMobileImg.css('background-image' , 'url('+v.visitPath+')');
                                    $('#editAdImageDiv').html(eachImg);
                                    $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                                    if($('[name=editAdTitle]').val()){
                                        $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                                    }

                                    break;
                                case "carousel":
                                    eachImg += '<li><div class="editAd-image-div" data-picture="'+ v.visitPath +'"><img class="editAd-image" src="'+ v.litImgURL +'"><input type="text" class="form-control" placeholder="'+I18N.getText('management', 'litImgTitle')+'"></div></li>';
                                    previewImgDiv.append('<li><img src="'+ v.visitPath +'" /></li>');
                                    previewInstgramImg.attr('src', v.visitPath);
                                    previewMobileImg.css('background-image' , 'url('+v.visitPath+')');
                                    $('#editAdImageDiv').html(eachImg);
                                    $('#editAdImageDiv').off('keyup','input.form-control:first').on('keyup','input.form-control:first',function() {
                                        if(Kit.isBlank($(this).val())){
                                            $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                                        }else{
                                            $('#preview-page').find('h4[name="previewAdTitle"]').html($(this).val());
                                        }
                                    })

                                    break;
                                case "video":
                                    eachImg += '<li><div class="editAd-image-div" data-picture="' + v.visitPath + '"><img class="editAd-image" src="' + v.litImgURL + '"></div></li>';
                                    previewImgDiv.append('<li><img src="'+ v.visitPath +'" /><div class="shipinCircle" style="background-image: url(./imgs/shipin.png);"></div></li>');
                                    previewInstgramImg.attr('src', v.visitPath);
                                    previewMobileImg.css('background-image' , 'url('+v.visitPath+')');
                                    $('#editAdImageDiv').append(eachImg);
                                    $('#editAdImageDiv li').css('width', '140px');
                                    $('#editAdImageDiv .editAd-image-div img').css('width', '140px');
                                    $("#editAdImageDiv").dragsort("destroy");
                                    if($('[name=editAdTitle]').val()){
                                        $('#preview-page').find('h4[name="previewAdTitle"]').html(Kit.isBlank($('[name=editAdTitle]').val()[0])? '&nbsp;' : $('[name=editAdTitle]').val()[0]);
                                    }
                                    break;
                            }
                        }
                    });
                });
                self.initPreviewImg();
                if(chooseType == 'carousel') {
                    self.carouselDrag();
                    $("#editAdImageDiv li").hover( function(event){
                        $(this).addClass('editAdImageDivHover');
                    },function(event){
                        $(this).removeClass('editAdImageDivHover');
                    });
                }
                $("#selectslogan").modal('hide');
            });
        }
        /*
         @获取视频数据
         */
        this.updateVideo = function(paramsApps){
            var body = {
                param: {}
            }

            //请求视频
            //TODO 应该实现按应用查询视频
            body.param.appNames = paramsApps ? paramsApps : [self.appName];
            body.param.sortList = [{
                "uploadTime": -1
            }]
            body.param = JSON.stringify(body.param);
            http.do("/adresource/getAdvideosAllList", body).then(function(result) {
                $("#selectVideoModal").find(".vid-list-box").empty();
                $("#selectVideoModal").find(".vid-list-box").append(self.initVideos(result));
                videoData = result.data; //存储视频原始数据
                self.action2();
                Kit.loading.hide('#selectslogan .modal-body');
            }, function() {});
        }
        this.playerVideo = function(e) {
            console.log(1111);
            var title = $(e.currentTarget).data('title');
            var videoUrl = $(e.currentTarget).data('video-url');
            if(videoUrl == '0') {
                Kit.alert2(I18N.getText('management', 'noVideoSource'));
                return;
            }
            var videoHtml = '<video controls="controls" class="embed-responsive-item"><source type=video/mp4 src="' + videoUrl + '"></video>'
            var $modal = $('#preview-player-video-modal');
            $modal.find('.modal-title').html(title);
            $modal.find('.modal-body div').html(videoHtml);
            $modal.modal('show');
            $modal.off('hide.bs.modal').on('hide.bs.modal', function(e) {
                $modal.find('.modal-body div').empty();
            });
        }
        /*
         @获取图片数据
         */
        this.update = function(event){
            Kit.loading.show('#selectslogan .modal-body');
            var body = {
                "appNames": apps,
                "languages": langs,
                "gender": gender, //1,2,3
                "isMy": false,
                "fbConnectionObjectIds": [self.appId]
            }
            // "resourceType": (dia == "carousels") ? "CAROUSEL" : "IMAGE"
            if (chooseType == "carousel") {
                body.resourceType = (chooseType == "carousel") ? "CAROUSEL" : "IMAGE";
                $('#selectslogan .square-priority').addClass('hidden');
            } else {
                var selectIns = ($.inArray('instagramstream', self.pageTypes) > -1); //是否有选择ins版位

                $('#picc .square-priority').tooltip({
                    placement: 'bottom'
                })

                body.days = day;

                // 点击了 排序按钮
                var resourceType = null;
                if (event) {
                    resourceType = $('#selectslogan .square-priority .fa-long-arrow-down').length > 0 ? 1 : -1;
                } else {
                    //支持ins 广告排序
                    if (selectIns) { //选择了 Ins 版位,初始打开窗口排在最前面
                        resourceType = 1;
                        $('#selectslogan .square-priority').find('.fa-long-arrow-up').removeClass('fa-long-arrow-up').addClass('fa-long-arrow-down');
                    } else {
                        resourceType = -1;
                        $('#selectslogan .square-priority').find('.fa-long-arrow-down').removeClass('fa-long-arrow-down').addClass('fa-long-arrow-up');
                    }
                }
                var hasResourceType = false;
                for (var i = sort.length - 1; i >= 0; i--) {
                    if (sort[i].resourceType) {
                        sort[i].resourceType = resourceType;
                        hasResourceType = true;
                        break;
                    }
                }
                if (!hasResourceType) {
                    sort.push({
                        resourceType: resourceType
                    })
                    sort = sort.reverse();
                }
                body.sortList = sort;
                // tipTitle('up');
                $('#selectslogan .square-priority').removeClass('hidden');
                $('#selectslogan').off('click', '.square-priority').on('click', '.square-priority', function(event) {
                    if ($(this).find('.fa-long-arrow-down').length > 0) {
                        $(this).find('.fa-long-arrow-down').removeClass('fa-long-arrow-down').addClass('fa-long-arrow-up');
                        self.tipTitle('up');
                    } else {
                        $(this).find('.fa-long-arrow-up').removeClass('fa-long-arrow-up').addClass('fa-long-arrow-down');
                        self.tipTitle('down');
                    }
                    self.update(event);
                });
            }

            http.do("/adresource/getAdimagesAllListMon", {
                param: JSON.stringify(body)
            }).then(function(result) {
                if(result.flag == 'success'){
                    var da = result.data?_.clone(result.data):[]; //[]
                    var fa = $("#selectslogan").find("ul.pics-box").empty();
                    imageData = da; //存储原始数据
                    var len = da.length; //直接渲染全部
                    fa.append(self.concrate(0, len, da)); //重新贴上去
                    self.action();
                }else{
                    Kit.alert2(result.msg);
                }
                Kit.loading.hide('#selectslogan .modal-body');
            });
        }
        /***
         ** 准备图片
         **/
        this.concrate = function (start, end, data) {
            var html = '';
            if (end == 0) {
                html = '<div class="modal-message">'+ I18N.getText('createAd', 'emptyMaterialToRemind') +'</div>';
            } else {
                for (var i = start; i < end; i++) {
                    var da = data[i];
                    var li = '<li class="container-fluid" data-imgid="' + da.id + '"> <img  class="img-thumbnail" width="100%" height="69%" src="' + da.litImgURL + '"> <div class="row-fluid"> <div class="col-md-4 col-sm-4"> <div>'+ I18N.getText('createAd', 'cost') +'</div> <div id="spent"  title="$' + (Kit.cent_to_dollar(da.spent || 0)) + '">$' + Kit.formatNumber((da.spent || 0) / 100) + '</div> </div> <div class="col-md-4 col-sm-4"> <div>'+ I18N.getText('createAd', 'install') +'</div> <div id="results" data-toggle="tooltip" title="' + (da.results || 0) + '">' + Kit.formatNumber(da.results || 0) + '</div> </div> <div class="col-md-4 col-sm-4"> <div>CTR</div> <div id="ctr">' + Kit.percentage(da.ctr || 0) + '</div> </div> <div class="adimage-create-time">' + Kit.formatTime(da.createTime) + '</div> </div> </li>';
                    if (chooseType != "img") {
                        li = '<li class="container-fluid container-fluid-car" data-imgid="' + da.id + '"><img  class="img-thumbnail" width="100%" height="69%" src="' + da.litImgURL + '"></li>';
                    }
                    html += li;
                }
            }
            return html;
        }
        /*****
         **图片列表加互动
         **/
        this.action = function() {
            $("ul.pics-box li").unbind("click").click(function(e) {
                if (chooseType == 'carousel')
                {
                    if ($(this).hasClass('active')) {
                        $(this).removeClass('active');
                    } else {
                        var len = $('#selectslogan .container-fluid.active').length;
                        if (len >= 5) {
                            Kit.alert2(I18N.getText('management', 'slideNumberMaxRemind', 5));
                        } else {
                            $(this).addClass("active");
                        }
                    }
                }
                else{
                    $(this).addClass("active").siblings().removeClass("active");
                }
            });

            $('#selectslogan .pic-pool img').each(function() {
                $(this).load(function() {
                    if (($(this)[0].naturalWidth > 0) && ($(this)[0].naturalWidth == $(this)[0].naturalHeight)) {
                        $(this).width(100)
                        $(this).height(100)
                    }
                });
            });
        };
        /**
         **视频列表加互动
         **/
        this.action2 = function() {
            $("ul.vid-list-box>li").unbind("click").click(function(e) {
                $(this).addClass("active").siblings().removeClass("active");
                $("#selectVideoModal .modal-footer .btn-primary").removeClass('hidden');
                $("#selectVideoModal .modal-footer .btn-primary").addClass('show');
            });
        }
        /**
         **
         **/
        this.initVideos = function(raw) {
            if (raw && typeof(raw) == "string") raw = JSON.parse(raw);
            var data = raw.data;
            var len = data.length;
            var html = '';
            if (len == 0) {
                html = '<div class="modal-message" style="padding-top: 140px;">'+ I18N.getText('createAd', 'emptyMaterialToRemind') +'</div>';
            } else {
                for (var i = 0; i < len; i++) {
                    var da = data[i];
                    html += '<li data-md5="' + da.md5 + '" data-litimgurl="'+da.litImgURL+'" data-visitpath="'+da.visitPath+'"><img width="100%" height="100%" src="' + da.litImgURL + '"><div class="caption">' + da.name.trim() + '</div></li>';
                }
            }
            return html;
        }
        /**
         * [tipTitle 1:1比例图片排序的提醒]
         * @return {[type]} [description]
         */
        this.tipTitle = function(arrow) {
            var title = ($('#picc .square-priority i.fa').hasClass('fa-long-arrow-up') ? I18N.getText('createAd', 'imageAlignmentToFront') : I18N.getText('createAd', 'imageAlignmentToBack'));
            $('#picc .square-priority').attr('data-original-title', title);
            $('#picc .square-priority').tooltip('hide');
        }
        /*
         @外链的三个输入框
         */
        this.initOutLink = function(){
            //var wAdDesc = $('textarea[name="w-ad-desc"]').val();
            //链接文字 显示网址事件
            $(".c-area textarea").on("input", function (e) {
                var _title = $(this).val().replace(/(^\s*)/g, "");
                var _maxlength = $(this).attr("maxlength");
                if (_maxlength && _maxlength > 0) {
                    _title = _title.substring(0, _maxlength);
                    var _length = _title.length;
                    $(this).parents(".c-area-container").find(".count").html(_maxlength - _length);
                }

                $(this).val(_title);
                var _span = $(this).parents(".c-area").find("span");
                _span.html(_title);
                $(this).css("height", _span.height() + "px");
            });
            //标题输入框禁止回车事件
            $(".c-area textarea").on("keydown", function (e) {
                //禁止回车
                if (e.keyCode == 13) {
                    return false;
                }
            });

        }

    };
    return me;
});
